package com.baizhi.config;

import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2019/4/19 0019.
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        /*定义一个过滤器*/
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        /*定义过滤链，即过滤规则*/
        Map map = new HashMap();
        /**
         * anon 不用登录就可以访问
         * authc 必须登录之后才可以访问
         */
        map.put("/**", "anon");
        map.put("/main/main.jsp", "authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        /*设置安全管理器*/
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        return shiroFilterFactoryBean;
    }


    /*创建securityManager*/
    @Bean
    public DefaultWebSecurityManager getSecurityManager(MyRealm myRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 设置自定义的realm
        securityManager.setRealm(myRealm);
        return securityManager;
    }

    /*创建myRealm*/
    @Bean
    public MyRealm getRealmDemo(CredentialsMatcher credentialsMatcher) {
        MyRealm myRealm = new MyRealm();

        /*设置使用密码凭证器*/
        myRealm.setCredentialsMatcher(credentialsMatcher);
        return myRealm;
    }

    /*设置密码凭证器*/
    @Bean
    public CredentialsMatcher getCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        // 设置算法的名字
        credentialsMatcher.setHashAlgorithmName("md5");
        // 设置散列次数
        credentialsMatcher.setHashIterations(1024);
        return credentialsMatcher;
    }

    /*开启shiro aop注解支持，使用代理模式，否则相关注解不会生效*/
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
